"""
点选验证码
"""
import os.path
import time

import cv2
from DrissionPage import ChromiumOptions, WebPage


def click_img():
    yzm_xy = []

    def mouse_callback(event, x, y, flags, param):
        if event == cv2.EVENT_LBUTTONDOWN:
            cv2.circle(img, (x, y), 3, (0, 0, 255), -1)
            print(f'鼠标点击处的像素坐标：({x}, {y})')
            yzm_xy.append({'x': x, 'y': y})

    # 点击图片并获得坐标
    img = cv2.imread('captcha.jpg')
    cv2.namedWindow('Image')
    cv2.setMouseCallback('Image', mouse_callback)
    cv2.imshow('Image', img)
    while True:
        cv2.imshow('Image', img)
        if cv2.waitKey(1) == 13:
            break
    cv2.destroyAllWindows()

    return yzm_xy


def crack_dx():
    dp = ChromiumOptions()
    # dp.no_imgs(True).mute(True)
    # dp.incognito()  # 匿名模式
    # dp.headless()  # 无头模式
    # dp.set_argument('--no-sandbox')  # 无沙盒模式
    # dp.set_argument('--disable-gpu')  # 禁用gpu加速
    dp.set_argument('--start-maximized')  # 设置启动时最大化
    # dp.set_argument('--disable-blink-features=AutomationControlled')
    # dp.set_user_agent(
    #     'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36')
    page = WebPage(mode='d', chromium_options=dp)
    page.get('http://www.ccgp-yunnan.gov.cn/page/procurement/procurementList.html')
    page.refresh()  # 重新加载页面
    page.wait(1)

    try:
        page.ele('text=>').click()  # 点击下一页
        page.wait(2)
        # 保存验证码图片
        print('要点击的文字: ', page.ele('@class=verify-msg').text)
        img_obj = page.ele('x://div[@class="verify-img-panel"]/img')
        if os.path.exists('./captcha.jpg'):
            os.remove('./captcha.jpg')
        img_obj.save('./', name='captcha.jpg')

        # 获取文字验证码点击位置
        yzm_xy = click_img()

        # 根据点击位置实现鼠标点击
        for xy in yzm_xy:
            page.actions.move_to(img_obj, offset_x=int(xy['x'] / 310 * 350), offset_y=int(xy['y'] / 155 * 175),
                                 duration=0.1).click()
            time.sleep(1)

        # 打印列表页数据
        for tr in page.eles('x://tr')[1:11]:
            tds = [td.text.strip() for td in tr.eles('x:td')]
            print(tds)

    finally:
        page.quit()


if __name__ == '__main__':
    crack_dx()
